package com.ruoyi.web.controller.task;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.task.domain.*;
import com.ruoyi.task.service.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 任务管理Controller
 * 
 * @author ruoyi
 * @date 2025-05-17
 */
@RestController
@RequestMapping("/system/management")
@Slf4j
public class TaskManagementController extends BaseController
{
    @Autowired
    private ITaskManagementService taskManagementService;

    @Autowired
    private ITaskExamineService taskExamineService;

    @Autowired
    private ITaskImageService iTaskImageService;

    @Autowired
    private ITaskUserService iTaskUserService;

    @Autowired
    private ITaskConfigService taskConfigService;

    @Autowired
    private ITaskDetailsService taskDetailsService;

    /**
     * 查询任务管理列表
     */
   // @PreAuthorize("@ss.hasPermi('system:management:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskManagement taskManagement)
    {
        startPage();
        List<TaskManagement> list = taskManagementService.selectTaskManagementList(taskManagement);
        return getDataTable(list);
    }


    @GetMapping("/getExamineData")
    public TableDataInfo getExamineData(TaskExamine taskExamine)
    {
        startPage();
        List<TaskExamine> list = taskExamineService.selectTaskExamineList(taskExamine);
        list.stream().forEach(taskExamine1 -> {
            TaskImage taskImage = new TaskImage();
            taskImage.setExamineId(taskExamine1.getId());
            List<TaskImage> taskImageList = iTaskImageService.selectTaskImageList(taskImage);
            taskExamine1.setTaskImages(taskImageList);
        });
        return getDataTable(list);
    }

    @ApiOperation(value = "申请任务")
    @PostMapping("/unifiedApplication")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult unifiedApplication(@RequestBody TaskExamine taskManagement)
    {
        log.info("申请任务："+taskManagement);
        if (taskManagement.getState().equals("1")){
            //成功
            TaskExamine taskExamine =  taskExamineService.selectTaskExamineById(taskManagement.getId());
            if (taskExamine != null){
                //更新用户完成字段,如果有父类给他对应的薪资
                TaskUser taskUser = new TaskUser();
                taskUser.setId(taskExamine.getUserId());
                taskUser.setComplete(1L);
                iTaskUserService.updateTaskUserById(taskUser);
                TaskUser user =  iTaskUserService.selectTaskUserById(taskExamine.getUserId());
                if (user != null && user.getReferenceId() != null){
                    TaskConfig taskConfig = taskConfigService.selectTaskConfigById(1L);
                    TaskUser taskUser1 = new TaskUser();
                    taskUser1.setId(user.getReferenceId());
                    taskUser1.setFreezeDeposits(taskConfig.getRewardAmount());
                    iTaskUserService.updateTaskUserAmountById(taskUser1);
                    TaskDetails taskDetails = new TaskDetails();
                    taskDetails.setUserId(taskExamine.getUserId());
                    taskDetails.setReferenceId(user.getReferenceId());
                    taskDetails.setAmount(taskConfig.getRewardAmount());
                    taskDetails.setType("0");
                    taskDetailsService.insertTaskDetails(taskDetails);
                }
                TaskManagement taskManagement1 =   taskManagementService.selectTaskManagementById(taskExamine.getTaskId());
                TaskConfig taskConfig = taskConfigService.selectTaskConfigById(1L);
                TaskUser taskUser1 = new TaskUser();
                taskUser1.setId(user.getId());
                taskUser1.setFreezeDeposits(taskManagement1.getReward());
                iTaskUserService.updateTaskUserAmountById(taskUser1);
                TaskDetails taskDetails = new TaskDetails();
                taskDetails.setUserId(taskExamine.getUserId());
                taskDetails.setReferenceId(user.getReferenceId());
                taskDetails.setAmount(taskManagement1.getReward());
                taskDetails.setTaskId(taskManagement.getId());
                taskDetails.setType("1");
                taskDetailsService.insertTaskDetails(taskDetails);
            }
        }
        return success(taskExamineService.updateTaskExamine(taskManagement));
    }

    /**
     * 导出任务管理列表
     */
   // @PreAuthorize("@ss.hasPermi('system:management:export')")
    @Log(title = "任务管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskManagement taskManagement)
    {
        List<TaskManagement> list = taskManagementService.selectTaskManagementList(taskManagement);
        ExcelUtil<TaskManagement> util = new ExcelUtil<TaskManagement>(TaskManagement.class);
        util.exportExcel(response, list, "任务管理数据");
    }

    /**
     * 获取任务管理详细信息
     */
  //  @PreAuthorize("@ss.hasPermi('system:management:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taskManagementService.selectTaskManagementById(id));
    }

    /**
     * 新增任务管理
     */
 //   @PreAuthorize("@ss.hasPermi('system:management:add')")
    @Log(title = "任务管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskManagement taskManagement)
    {
        return toAjax(taskManagementService.insertTaskManagement(taskManagement));
    }

    @PostMapping("updateType")
    public AjaxResult updateType(@RequestBody TaskManagement taskManagement)
    {
        return toAjax(taskManagementService.updateTaskManagement(taskManagement));
    }

    /**
     * 修改任务管理
     */
   // @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "任务管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskManagement taskManagement)
    {
        return toAjax(taskManagementService.updateTaskManagement(taskManagement));
    }

    /**
     * 删除任务管理
     */
  //  @PreAuthorize("@ss.hasPermi('system:management:remove')")
    @Log(title = "任务管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        taskExamineService.deleteTaskExamineByIds(ids);
        return toAjax(taskManagementService.deleteTaskManagementByIds(ids));
    }
}
